import { Breadcrumb, Button, Card, Form,  Radio, Select,DatePicker, Table, Tag, Space, message, Modal } from 'antd';
import {  EditOutlined ,DeleteOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom';
import React, { useEffect, useRef, useState } from 'react'

import errorSRC from 'assets/error.png'
import Channel from 'components/Channel';
// 导入API
import {getChannelsAPI} from 'api/channel'
import {delArticleAPI, getArticleAPI} from 'api/article'
import { useHistory } from 'react-router-dom';

const { Option } = Select;
const { RangePicker } = DatePicker;



export default function ArticleList() {
  const history =  useHistory()
  // 定义状态列的颜色
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  // 2.申明state
  // const [channelList, setChannelList] = useState([])
  const [articleData, setArticleData] = useState({})

  // 表格 列数据
  const columns = [
    {
      // title控制表头文字显示
      title: '封面',
      // 有dataIndex 可以1省略key
      dataIndex: 'cover',
      // key指定唯一列
      // key: 'name',
      // 自定义渲染内容 , 类似插槽
      render : (value) => {
        if(!value.images.length){
          return <img width="100" height="60" src={errorSRC} alt="" />
        }
        return <img width="100" height="60" src={value.images[0]} alt="" />
      }
    },
    {
      title: '标题',
      dataIndex: 'title'
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        const info = articleStatus.find((item) => item.id === value)
        return <Tag color={info.color}>{info.name}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count'
    },
    {
      title: '操作',
      render : (value,record) => {
        return (
        <Space>
          {/* 1. 添加click事件 */}
            {/* 2. 跳转路由，记得传参id */}
            <Button
              onClick={() => history.push('/edit/' + record.id)}
              shape="circle"
              type="primary"
              icon={<EditOutlined />}
            ></Button>
          <Button danger icon={<DeleteOutlined />} onClick={() =>handleDelete(record)}></Button>
        </Space>)
      }
    }
  ];
  
  // 点击删除事件
  const handleDelete =  (record) => {
    Modal.confirm({
      title: '温馨提示',
      content: '你确定要删除嘛',
      // onOK改为异步函数
      onOk:async () => {
        // 点击删除发送请求
        await delArticleAPI(record.id)
        // 重新请求刷新页码 , 加回查询参数
        const formData = formDataRef.current||{}
        const pageData = pageInfoRef.current||{}
        // 删除成功后,刷新界面,传入分页参数
        loadArticlesDate({...formData,...pageData})
        // 用户提示
        message.success('删除成功')
      }
    })
    
  }

  const handleFinish=(values) => {
    // 收集数据
    console.log('values ----->  ', values);
    let formData = {...values};
    if(values.status){
      delete formData.status
    }
    if(values.date){
      // 4.修复日期进准度的问题
      const startTime = values.date[0].startOf('day').format('YYYY-MM-DD HH-mm-ss')
      const endTime = values.date[0].endOf('day').format('YYYY-MM-DD HH-mm-ss')
      formData.begin_pubdate=startTime
      formData.end_pubdate=endTime
      delete formData.date
    }
    // 2. .current分配表单数据
    formDataRef.current=formData
    // 自己组装成后台需要的格式
    console.log('formData  ----->  ', formData);
    // 3.筛选完讲对象传入,提交时发请求
    loadArticlesDate(formData)
  }


  // 1.创建ref
  const formDataRef = useRef(null)
  // 改变页码事件
  const handleChange=(page,pageSize) => {
    // console.log('page, pageSize  ----->  ', page, pageSize);
    // 1.改造参数为对象
    // 3.当分页时 ,从ref中取出数据,添加到请求
    // 分页时存入数据 
    pageInfoRef.current ={page,per_page:pageSize}
    loadArticlesDate({page,per_page:pageSize,...(formDataRef.current||{})})
  }

  // 1.创建ref 准备存储分页数据
  const pageInfoRef = useRef(null)


  // const loadChannelList = async () =>{
  //   const res = await getChannelsAPI()
  //   console.log('res  ----->  ', res);
  //   setChannelList(res.data.channels)
  // }
  
  // 2.改造参数方式
  const loadArticlesDate = async (params) =>{
    const res = await getArticleAPI(params)
    console.log('res  ----->  ', res);
    setArticleData(res.data)
  }
  // 3.挂载后发请求
  useEffect(() => {
    // loadChannelList()
    loadArticlesDate()
  }, [])
  return (
    <div>
      <Card title={
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to="/home">首页</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            文字详情
          </Breadcrumb.Item>
        </Breadcrumb>
      } bordered={false} >
        <Form
          onFinish={handleFinish}
          autoComplete="off"
          initialValues={{status:-1,channel_id:1}}
        >
            <Form.Item label="状态" name='status'>
              <Radio.Group>
                <Radio value={-1}>全部</Radio>
                <Radio value={0}>草稿</Radio>
                <Radio value={1}>待审核</Radio>
                <Radio value={2}>审核通过</Radio>
                <Radio value={3}>审核失败</Radio>
              </Radio.Group>
            </Form.Item>

            {/* 3. 验证是否能够使用 */}
            <Form.Item label="频道" name='channel_id2'>
                <Channel style={{ width: 200 }}></Channel>
            </Form.Item>

            <Form.Item label="日期" name='date'>
              <RangePicker />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>

          {/* colums控制列显示 , dataSource控制每行数据 , rowKey表格行 key 的取值*/}
          <Table columns={columns} dataSource={articleData.results} rowKey='id' 
            pagination={{
              // 点击切换页面
              onChange : handleChange,
              pageSize:articleData.per_page,
              total:articleData.total_count,
              current:articleData.page,
              position:['bottomCenter']
            }}/>
      </Card>
    </div>
  );
  
}

